import React from 'react';
import PropTypes from 'prop-types';
import './index.scss';
import ReactDOM from 'react-dom';

export default class Dialog extends React.Component {
  static propTypes = {
    show: PropTypes.bool.isRequired,
    title: PropTypes.node,
    buttons: PropTypes.node,
    onClose: PropTypes.func
  }

  constructor(props) {
    super(props);
    this.state = {
      innerShow: props.show || false
    };
  }

  onMaskClick = () => {
    this.onCloseClick();
  }

  onCloseClick = () => {
    const { onClose } = this.props;
    if (onClose) {
      if (onClose() === false) {
        this.setState({
          innerShow: false
        });
      }
    } else {
      this.setState({
        innerShow: false
      });
    }
  }

  componentWillReceiveProps(nextProps) {
    const { show } = nextProps;
    if (this.state.innerShow !== show) {
      this.setState({
        innerShow: show
      });
    }
  }

  render() {
    const { title, children, buttons, closeTheme = '', className='', hasMask = false, width = 320 } = this.props;
    if (!this.state.innerShow) {
      return null;
    }
    return (
      <React.Fragment>
        { hasMask && <div className="erayt-mask" onClick={this.onMaskClick} /> }
        <div className={`erayt-dialog ${className}`} style={{width}}>
          <div className="erayt-dialog-title bottom-line">
            {title}
            <svg className={`erayt-dialog-close ${closeTheme} icon`} aria-hidden="true" onClick={this.onCloseClick}><use xlinkHref="#icon-close" /></svg>
          </div>
          <div className="erayt-dialog-content">
            {children}
          </div>
          <div className="erayt-dialog-buttons">
            {buttons}
          </div>
        </div>
      </React.Fragment>
    );
  }
}

Dialog.show = (options) => {
  const { isShow = true, title = '对话框', content, className = '', onClose, hasMask = false } = options;
  if (isShow) {
    const reactDom = (
        <Dialog
            show={isShow}
            title={title}
            className={className}
            hasMask={hasMask}
            onClose={
              () => {
                Dialog.dialog({ isShow: false });
                onClose && onClose;
              }
            }
        >
          { content }
        </Dialog>
    );
    let dom = document.getElementById('outer-dialog');
    if (!dom) {
      dom = document.createElement('div');
      dom.id = 'outer-dialog';
      document.body.appendChild(dom);
    }
    ReactDOM.render(
        reactDom,
        dom,
    );
  } else {
    const dom = document.getElementById('outer-dialog');
    if (dom) {
      dom.parentNode.removeChild(dom);
    }
  }
}
